const express = require('express')
const router = express.Router()
const db = require('../config/db')
const ipToCity = require('../utils/ipToCity')
const defaulAvatar =
  'https://cdn.z.wiki/autoupload/20250511/XTyv/770X778/df-avatar.png'

// 获取评论列表
router.get('/list', async (req, res) => {
  try {
    const { articleId, page = 1, pageSize = 10 } = req.query
    const offset = (page - 1) * pageSize

    if (!articleId) {
      return res.status(400).json({
        data: null,
        message: '缺少文章ID',
        code: 400,
      })
    }

    // 获取主评论，并从用户表中获取头像
    const [comments] = await db.query(
      `SELECT comments.*, 
          COALESCE(users.avatar_url, ?) AS user_avatar 
   FROM comments 
   LEFT JOIN users ON comments.user_id = users.id 
   WHERE comments.article_id = ? AND comments.parent_id IS NULL AND comments.deleted_at IS NULL
   ORDER BY comments.created_at DESC LIMIT ? OFFSET ?`,
      [defaulAvatar, articleId, parseInt(pageSize), offset]
    )

    // 获取每个主评论的回复
    for (let comment of comments) {
      const [replies] = await db.query(
        `SELECT comments.*, 
                COALESCE(users.avatar_url, ?) AS user_avatar 
         FROM comments 
         LEFT JOIN users ON comments.user_id = users.id 
         WHERE comments.parent_id = ? AND comments.deleted_at IS NULL
         ORDER BY comments.created_at ASC`,
        [defaulAvatar, comment.id]
      )
      comment.replies = replies
    }

    // 获取评论总数
    const [totalCount] = await db.query(
      'SELECT COUNT(*) as total FROM comments WHERE article_id = ? AND parent_id IS NULL AND deleted_at IS NULL',
      [articleId]
    )

    res.json({
      data: {
        list: comments,
        total: totalCount[0].total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
      },
      message: '获取成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 发布评论
router.post('/publish', async (req, res) => {
  try {
    const { articleId, content, userId, userName, userAvatar } = req.body

    if (!articleId || !content) {
      return res.status(400).json({
        data: null,
        message: '缺少必要参数',
        code: 400,
      })
    }

    // 默认头像URL

    // 获取客户端IP地址
    const ip =
      req.headers['x-forwarded-for']?.split(',')[0] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.ip ||
      '0.0.0.0'

    // 将IP转换为城市名称
    const publishLocation = await ipToCity(ip)

    // 处理游客评论
    const nickname = userName || `${publishLocation}网友`
    const avatar = userAvatar || defaulAvatar

    const [result] = await db.query(
      `INSERT INTO comments 
       (article_id, user_id, user_nickname, user_avatar, content, comment_ip) 
       VALUES (?, ?, ?, ?, ?, ?)`,
      [articleId, userId || null, nickname, avatar, content, publishLocation]
    )

    // 更新文章评论数
    await db.query(
      'UPDATE articles SET comment_count = comment_count + 1 WHERE id = ?',
      [articleId]
    )

    res.status(201).json({
      data: { id: result.insertId },
      message: '评论成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 回复评论
router.post('/reply', async (req, res) => {
  try {
    const {
      article_id,
      parent_id,
      content,
      user_id,
      user_nickname,
      user_avatar,
      comment_ip,
    } = req.body

    if (!article_id || !parent_id || !content || !comment_ip) {
      return res.status(400).json({
        data: null,
        message: '缺少必要参数',
        code: 400,
      })
    }

    // 处理游客评论
    const nickname = user_nickname || `${comment_ip}网友`
    const avatar = user_avatar || defaulAvatar

    const [result] = await db.query(
      `INSERT INTO comments 
       (article_id, parent_id, user_id, user_nickname, user_avatar, content, comment_ip) 
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [
        article_id,
        parent_id,
        user_id || null,
        nickname,
        avatar,
        content,
        comment_ip,
      ]
    )

    // 更新文章评论数
    await db.query(
      'UPDATE articles SET comment_count = comment_count + 1 WHERE id = ?',
      [article_id]
    )

    res.status(201).json({
      data: { id: result.insertId },
      message: '回复成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 删除评论（软删除）
router.post('/delete', async (req, res) => {
  try {
    const { id, user_id, article_id } = req.body

    if (!id || !article_id) {
      return res.status(400).json({
        data: null,
        message: '缺少必要参数',
        code: 400,
      })
    }

    // 检查评论是否存在
    const [comments] = await db.query(
      'SELECT * FROM comments WHERE id = ? AND deleted_at IS NULL',
      [id]
    )

    if (comments.length === 0) {
      return res.status(404).json({
        data: null,
        message: '评论不存在',
        code: 404,
      })
    }

    // 检查是否有权限删除（用户只能删除自己的评论）
    if (user_id && comments[0].user_id !== user_id) {
      return res.status(403).json({
        data: null,
        message: '无权限删除该评论',
        code: 403,
      })
    }

    // 软删除评论
    await db.query(
      'UPDATE comments SET deleted_at = CURRENT_TIMESTAMP WHERE id = ? OR parent_id = ?',
      [id, id]
    )

    // 更新文章评论数
    const [replies] = await db.query(
      'SELECT COUNT(*) as count FROM comments WHERE parent_id = ? AND deleted_at IS NULL',
      [id]
    )
    const decrementCount = 1 + replies[0].count // 主评论 + 回复数

    await db.query(
      'UPDATE articles SET comment_count = comment_count - ? WHERE id = ?',
      [decrementCount, article_id]
    )

    res.json({
      data: null,
      message: '删除成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

module.exports = router
